<template>
  <div class="schedule-view">
    <div class="ele-schedule">
      <div class="op-btn-group">
        <px-button type="primary" v-has="'ERC_CALENDAR_CALENDAR_INPORT'" @click="handleImport">导入排班</px-button>
        <px-button underline type="primary" v-has="'ERC_CALENDAR_CALENDAR_DOWNLOAD'" link icon="download" @click="downloadTmp">下载模板</px-button>
      </div>
      <div class="calendar-container">
        <px-calendar class="calendar-content" ref="calendar" v-model="currentDate">
          <template #header="{ date }">
            <div class="canlendar-title">
              <px-form ref="formRef" class="schedule" :model="queryParams" label-position="right" label-width="40px">
                <FactoryArea :defaultSelected="true" :factoryArea="queryParams.factoryId" @changeFactoryArea="changeFactoryArea" />
              </px-form>
              <px-button :disabled="loading" @click="selectDate('prev-month')"
                ><px-icon><ArrowLeft /></px-icon>上个月</px-button
              >
              &nbsp;
              <span>{{ date }}</span>
              &nbsp;
              <px-button :disabled="loading" @click="selectDate('next-month')"
                >下个月<px-icons><ArrowRight /></px-icons
              ></px-button>
              &nbsp;&nbsp;&nbsp;
              <px-button type="primary" :disabled="loading" @click="selectDate('today')">今天</px-button>
            </div>
          </template>
          <template #date-cell="{ data }">
            <div class="cell-content" :class="checkHoliday(data.day) ? 'is-holiday' : ''">
              <div class="day">{{ data.day.split("-")[2] }}<span v-if="checkHoliday(data.day)" class="holiday-tip">（休）</span></div>
              <div class="s-type">
                <div v-for="(item, index) in cellContent(data.day)" :key="item.label" class="type-item">
                  <ul :class="['personGroup', { top: ind === 0 }]" v-for="(personGroup, ind) in item.data" :key="ind">
                    <li class="dutyLevel">
                      <span class="dutyLevelLabel" v-if="index === 0">{{ personGroup.label }}</span>
                      <px-popover ref="popover" placement="top-start" title="人员" :width="250">
                        <template #reference>
                          <div :class="['person', { firstPerson: ind === 0 }]">
                            <div v-for="person in personGroup.data.slice(0, 2)" :key="person.id">
                              <px-text class="employeeName" truncated>{{ person.employeeName }}</px-text>
                              <px-text truncated>{{ person.phoneNumber }}</px-text>
                            </div>
                            <div v-if="personGroup.data.length > 2" class="more">
                              ... <span class="badge">{{ personGroup.data.length - 2 }}</span>
                            </div>
                          </div>
                        </template>
                        <div class="person pop-person">
                          <div v-for="(person, personInd) in personGroup.data" :key="person.id">
                            {{ `${personGroup?.data?.length > 1 ? `${personInd + 1}、` : ""}` }}{{ person.employeeName }}-{{ person.phoneNumber }}
                          </div>
                        </div>
                      </px-popover>
                    </li>
                  </ul>
                  <div class="type">{{ item.label }}</div>
                </div>
              </div>
            </div>
          </template>
        </px-calendar>
      </div>
    </div>
    <!-- 上传文件 -->
    <div v-if="fileUploadVisible">
      <FileUpload ref="uploadRef" v-model:visible="fileUploadVisible" @uploadAction="fileUploadConfirm" />
    </div>
    <!-- 上传文件报错 -->
    <px-dialog v-model="fileErrorVisible" title="文件上传失败" width="50%">
      <px-table :data="fileErrorInfo" class="erc-table" size="small" height="350px" border>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :min-width="item.minWidth"
          :show-overflow-tooltip="item.showOverflowTooltip"
        >
          <template #default="scope">{{ scope.row[item.prop] ? scope.row[item.prop] : "-" }}</template>
        </px-table-column>
      </px-table>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="download">下载</px-button>
          <px-button type="primary" @click="fileErrorVisible = false">确认</px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import { importDuty, queryDetail } from "@/api/erc/duty";
import { queryMonthHoliday } from "@/api/handover";
import { downloadDataByExcel } from "@/utils/pengxi";
import FileUpload from "@/views/common/handleover/components/fileUpload.vue";
import FactoryArea from "@/views/erc/inspect/components/FactoryArea.vue";
import dayjs from "dayjs";
import { PxMessage } from "px-ui";
import { getCurrentInstance, ref, watchEffect } from "vue";

defineOptions({
  name: "ERC_CALENDAR_CALENDAR"
});
const calendar = ref();
const currentDate = ref(new Date());
const currentMonth = ref();
const scheduleData = ref<any[]>([]);
const holidayData = ref<any[]>([]);
const fileUploadVisible = ref(false);
const fileErrorVisible = ref(false);
const fileErrorInfo = ref([]);
const loading = ref(false);
const tableColumns = [
  { prop: "errorRow", label: "错误行", minWidth: "60", showOverflowTooltip: true },
  { prop: "errorMessage", label: "错误详情", minWidth: "180", showOverflowTooltip: true }
];
const queryParams = ref<any>({});
// 地块改变
const changeFactoryArea = (value: any) => {
  queryParams.value.factoryId = value;
  getScheduleData(true);
};
const { proxy } = getCurrentInstance();
const downloadTmp = async () => {
  await (proxy as any).download("GET", "/erc/api/v1/duty/template/download", {}, "消控室值班日历模板.xlsx");
  PxMessage.success("模板已下载");
};
const handleImport = () => {
  fileUploadVisible.value = true;
};
const download = () => {
  const date = dayjs().format("YYYYMMDDHHmmss");
  downloadDataByExcel(tableColumns, fileErrorInfo.value, `ERC消控室值班日历文件上传报错_${date}.xlsx`);
};
const fileUploadConfirm = async fileList => {
  fileErrorInfo.value = [];
  let formData = new FormData();
  // formData.append("classCode", routerStore.getSubject === "ALL" ? "" : routerStore.getSubject);
  formData.append("file", fileList[0].raw);
  const fileData: any = await importDuty(formData);
  if (fileData.result === false) {
    fileErrorInfo.value = fileData.errors || [];
    fileErrorVisible.value = true;
  } else {
    fileUploadVisible.value = false;
    PxMessage.success("上传成功");
    getScheduleData(true);
  }
  // state.closeEventFormParams.file = fileData;
};

const selectDate = val => {
  if (!calendar.value) return;
  calendar.value.selectDate(val);
};

const getScheduleData = async (flag = false) => {
  const oDate = currentDate.value ? new Date(currentDate.value) : new Date();
  const oYear = oDate.getFullYear();
  const oMonth = oDate.getMonth() + 1;
  if ((currentMonth.value === oMonth && !flag) || !queryParams.value.factoryId) {
    return;
  }
  currentMonth.value = oMonth;
  try {
    loading.value = true;
    const sdata: any = await queryDetail({
      ...queryParams.value,
      startTime: dayjs(`${oYear}-${oMonth}`).startOf("month").format("YYYY-MM-DD 00:00:00"),
      endTime: dayjs(`${oYear}-${oMonth}`).endOf("month").format("YYYY-MM-DD 23:59:59")
    });
    scheduleData.value = sdata?.data || [];
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
  const hdata: any = await queryMonthHoliday({ scheduleMonth: dayjs(oDate).format("YYYY-MM") });
  holidayData.value = hdata;
};
const cellContent = date => {
  // 根据日期筛选
  let list = scheduleData.value.filter(item => {
    const { startTime, endTime } = item;
    const startFlag = new Date(`${date} 00:00:00`).getTime() >= new Date(startTime).getTime();
    const endFlag = new Date(`${date} 00:00:00`).getTime() <= new Date(endTime).getTime();
    return startFlag && endFlag;
  });
  const isThisMonth = new Date(date).getMonth() === new Date(currentDate.value).getMonth();
  if (list.length && isThisMonth) {
    // const dayList = list.filter(item => item.dutyType === "白班");
    // const nightList = list.filter(item => item.dutyType === "夜班");
    const mapConfig = [
      ["白班", ["主班", "副班"]],
      ["夜班", ["主班", "副班"]]
    ];
    const newList = [];
    mapConfig.forEach(item => {
      const data = (item[1] as string[]).map(dutyLevelItem => {
        const arr = list.filter(listItem => listItem.dutyType === item[0] && listItem.dutyLevel === dutyLevelItem);
        return { label: dutyLevelItem, data: arr };
      });
      newList.push({
        label: item[0],
        data
      });
    });
    return newList;
  }
  return [];
};
const checkHoliday = date => {
  let list = holidayData.value.filter(item => item.holidayDate == date);
  if (list.length) {
    return true;
  }
  return false;
};
watchEffect(() => {
  getScheduleData();
});
</script>
<style scoped lang="scss">
:deep(.px-select) {
  width: 100%;
}

:deep(.px-input) {
  width: 100%;
}
.schedule-view {
  height: 100%;
}

.erc-table {
  --px-table-border-color: #dfdfdf;

  font-size: 14px;

  :deep(.allSelectDisable .cell) {
    visibility: hidden;
  }

  :deep(.px-table__header) {
    thead {
      tr {
        background-color: #e7eefb !important;

        th {
          font-size: 14px;
          font-weight: bold;
          color: #000;
          background-color: #e7eefb !important;
        }
      }
    }
  }

  :deep(.px-table__cell) {
    padding: 0;
    height: 36px;
    line-height: 36px;

    .cell {
      height: 36px;
      line-height: 36px;
    }
  }
}

.ele-schedule {
  display: flex;
  flex-direction: column;
  padding: 16px 24px 20px;
  background: #fff;

  .op-btn-group {
    text-align: right;
  }

  .calendar-container {
    flex-grow: 1;
    .canlendar-title {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      position: relative;
    }
    .schedule {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
    .personGroup {
      height: 50%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      &.top {
        border-bottom: 1px solid #ddd;
      }
    }
    .dutyLevel {
      width: 100%;
      display: flex;
      padding: 8px 4px;
      color: #333;
      position: relative;
      .dutyLevelLabel {
        flex-shrink: 0;
        font-weight: bold;
      }
      .firstPerson {
        font-weight: bold;
      }
    }
  }
  .calendar-content {
    height: 100%;
    display: flex;
    flex-direction: column;
    :deep(.px-calendar__header) {
      padding: 16px 0;
    }
    :deep(.px-calendar__body) {
      flex-grow: 1;
      padding: 0;
    }
  }
}

:deep(.px-calendar-table) {
  height: 100%;
  --px-font-size-base: 12px;
  .px-calendar-day {
    height: 100%;
    padding: 0 !important;
    overflow: hidden;
  }
  .cell-content {
    height: 100%;
  }

  td {
    border-color: #999 !important;
  }
}
:deep(.px-form-item) {
  margin-bottom: 0;
}

.px-calendar-table {
  .px-calendar-day {
    padding: 0;

    .cell-content {
      position: relative;

      .day {
        position: absolute;
        top: 5px;
        left: 5px;
        z-index: 2;
        font-size: 14px;
        font-weight: bold;

        .holiday-tip {
          color: red;
        }
      }

      .s-type {
        display: flex;
        height: 210px;

        .type-item {
          position: relative;
          flex: 1;
          padding-top: 21px;
          font-size: 13px;
          text-align: center;

          .person {
            padding-left: 4px;
            font-size: 14px;
            line-height: 16px;
            text-align: left;
            text-align: center;
            flex-grow: 1;
            overflow: hidden;
          }

          .type {
            position: absolute;
            top: 5px;
            right: 5px;
            font-weight: bold;
          }

          .more {
            position: absolute;
            right: 0;
            bottom: 0;
            font-size: 14px;
            font-weight: bold;
            letter-spacing: 2px;

            .badge {
              display: inline-block;
              width: 14px;
              height: 14px;
              font-size: 12px;
              line-height: 14px;
              color: #fff;
              text-align: center;
              background: #3b82f6;
              border-radius: 14px;
            }
          }

          &:nth-child(n + 1) {
            background: #fff9e6;
            overflow: hidden;
            .type {
              color: #000;
            }
          }

          &:nth-child(n + 2) {
            background: #ecf3ff;

            .type {
              color: #3b82f6;
            }
          }
        }
      }

      &.is-holiday {
        .s-type {
          background: #f5f5f5 !important;

          .type-item {
            background: #f5f5f5 !important;
          }
        }
      }
    }
  }
}

.px-popper {
  .px-popover__title {
    font-weight: bold;
  }
  .pop-person {
    line-height: 1.6;

    > div {
      position: relative;
      padding-left: 16px;

      &::before {
        position: absolute;
        top: 8px;
        left: 0;
        display: inline-block;
        width: 6px;
        height: 6px;
        content: "";
        background: #3b82f6;
        border-radius: 6px;
      }
    }
  }
}
.employeeName {
  font-size: 14px;
}
</style>
